<template>
  <div id="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column label="#" type="index" width="50" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="updataState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="findDate(scope.row.id)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="del(scope.row.id)"
            />
            <el-tooltip effect="dark" content="分配权限" placement="top">
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addVisible"
      width="36%"
      @close="addClosed"
    >
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addRuleForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editVisible"
      width="36%"
      @close="editClosed"
    >
      <el-form
        :model="editRuleForm"
        :rules="editRules"
        ref="editRuleForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import "../assets/css/users/users.scss";

export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmial = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)$/;
      if (regEmial.test(value)) {
        callback();
      } else {
        callback(new Error("邮箱格式不正确"));
      }
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (regMobile.test(value)) {
        callback();
      } else {
        callback(new Error("电话格式不正确"));
      }
    };
    return {
      tableData: [],
      total: 0,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      addRuleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editRuleForm: {
        username: "",
        email: "",
        mobile: "",
      },
      addVisible: false,
      editVisible: false,
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.axios.get("/users", {
        params: this.queryInfo,
      });
      if (res.meta.status == 200) {
        this.tableData = res.data.users;
        this.total = res.data.total;
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    async updataState(val) {
      const { data: res } = await this.axios.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
      } else {
        this.$message.error(res.meta.msg);
        res.meta.status = !res.meta.status;
      }
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUsersList();
    },
    submitForm() {
      this.$refs.addRuleForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.axios.post(
            "users",
            this.addRuleForm
          );
          if (res.meta.status == 201) {
            this.$message.success(res.meta.msg);
            this.getUsersList();
            this.addVisible = false;
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          return false;
        }
      });
    },
    addClosed() {
      this.$refs.addRuleForm.resetFields();
    },
    editClosed() {
      this.$refs.editRuleForm.resetFields();
    },
    async findDate(val) {
      this.editVisible = true;
      const { data: res } = await this.axios.get(`users/${val}`);
      this.editRuleForm = res.data;
    },
    async editSubmitForm() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.axios.put(
            `users/${this.editRuleForm.id}`,
            this.editRuleForm
          );
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            this.editVisible = false;
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          return false;
        }
      });
      this.getUsersList();
    },
    async del(val) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        const { data: res } = await this.axios.delete(`users/${val}`);
        if (res.meta.status == 200) {
          this.$message.success(res.meta.msg);
          this.getUsersList();
        } else {
          this.$message.error(res.meta.msg);
        }
      } else if (res == "cancel") {
        this.$message.info("已取消删除");
      }
    },
  },
  created() {
    this.getUsersList();
  },
};
</script>

<style scoped></style>
